<template>
    <div>
        <div class="dialog">
            <div id="dialog-content" ref="dialogRef"></div>

        </div>
        <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" placeholder="请输入内容" v-model="inputText"
            id="message-input">
        </el-input>
        <el-button type="primary" @click="sendMsg">发送</el-button>
    </div>

</template>
<script lang="ts" setup name="ChatGlm">
import { onMounted, ref, Ref } from 'vue';
import axios, { AxiosProgressEvent } from 'axios';
import { Message } from 'element-ui';

const dialogRef: Ref<any> = ref(null);
const inputText: Ref<string> = ref('');
const url = 'http://10.63.132.22:9002/v1/chat/completions'

const sendMsg = () => {
    console.log('sendMsg');
    dialogRef.value.innerHTML += '<div class="dialog__item dialog__item--user">' + inputText.value + '</div>';
    axios({
        method: 'post',
        url,
        data: {
            "model": "string",
            "messages": [
                {
                    "role": "user",
                    "content": inputText.value
                }
            ],
            "temperature": 0,
            "top_p": 0,
            "max_length": 0,
            "stream": true
        },
        responseType: 'stream',
        onDownloadProgress: function (progressEvent: AxiosProgressEvent) {
            setData0(progressEvent.event.currentTarget.responseText)
        },
        // signal: controller.signal
    }).then(() => {

        // setData0(res)
        // setLoading(false)
    }).catch(() => {
        Message.error('请求失败')
    })

    const setData0 = (res: any) => {

        // 将字符串分割成多个JSON对象
        const data = res.replace(/^data:\n\n\n\n/, '')
            ?.split('data:')
            ?.map((item: string) => item.replace(/\n\n$/, '')).filter((str: string) => str.trim() !== '')

        let content = '';
        console.log(content)

        // 遍历每个JSON对象
        for (const jsonString of data) {
            try {
                // 解析JSON对象
                const obj = JSON.parse(jsonString);
                // console.log('解析', obj)
                // 检查对象是否包含"choices"属性
                if (obj.choices && Array.isArray(obj.choices)) {
                    // 遍历"choices"数组
                    for (const choice of obj.choices) {
                        // 检查"delta"对象是否包含"content"属性
                        if (choice.delta && typeof choice.delta.content === 'string') {
                            // 将"content"的值添加到结果字符串中
                            content += choice.delta.content;
                            dialogRef.value.innerHTML += '<span>' + choice.delta.content + '</span>';
                        }
                    }
                }
            } catch (e) {
                console.error('Failed to parse JSON string:', jsonString, e);
            }
        }

        // console.log('结果', content);
        // const modelResponse = data.choices[0].delta.content;

        // dialogRef.value.innerHTML += '<div class="dialog__item dialog__item--model">' + content + '</div>';
        dialogRef.value.scrollTop = dialogRef.value.scrollHeight;
    };

    // let buffer = '';

    // const setData = (res: any) => {
    //     // 将新接收到的数据添加到缓冲区
    //     buffer += res;

    //     // 尝试找到一个完整的JSON对象
    //     const endOfObjectIndex = buffer.indexOf('}');
    //     console.log('解析1', endOfObjectIndex);
    //     if (endOfObjectIndex !== -1) {
    //         // 我们找到了一个完整的JSON对象
    //         const jsonString = buffer.substring(0, endOfObjectIndex + 1);

    //         // 从缓冲区中移除这个对象
    //         buffer = buffer.substring(endOfObjectIndex + 2);

    //         // 处理JSON对象
    //         try {
    //             const obj = JSON.parse(jsonString);
    //             console.log('解析', obj);
    //             if (obj.choices && Array.isArray(obj.choices)) {
    //                 for (const choice of obj.choices) {
    //                     if (choice.delta && typeof choice.delta.content === 'string') {
    //                         console.log('Content:', choice.delta.content);
    //                         dialogRef.value.innerHTML += '<span class="">' + choice.delta.content + '</span>';
    //                     }
    //                 }
    //             }
    //         } catch (e) {
    //             console.error('Failed to parse JSON string:', jsonString, e);
    //         }
    //     }
    // };

};
// https://juejin.cn/post/7237426124669157433?from=search-suggest 参考使用fetch
onMounted(() => {
    axios.get("https://mastest.changan.com.cn/am_rest/qtm/v2/getWordOrderList?questionId=81415bc0-e37d-4887-b199-6fde82a131ff", {
        headers: {
            identityToken: "a975ccdd-d798-4d34-af61-7a57fb0d0135"
        }
    })
})
</script>
<style lang="scss" scoped>
.dialog {
    border: 1px solid black;
    border-radius: 5px;
    box-shadow: 2px 2px 5px gray;
    padding: 10px;
    width: 500px;
    height: 300px;
    overflow-y: auto;
}

.dialog__item {
    margin-bottom: 10px;
}

.dialog__item--user {
    text-align: right;
}

.dialog__item--model {
    text-align: left;
}

.el-textarea {
    margin: 15px 0;
}
</style>